package com.remote.server.handle;

import com.remote.common.RemoteFactory;
import com.remote.common.model.ClientInfo;
import com.remote.common.model.Request;
import com.remote.common.model.Response;
import com.remote.common.model.ServerClientInfo;
import com.remote.common.util.Utils;
import io.netty.channel.ChannelHandlerContext;

/**
 * 初始连接处理
 */
public class ConnectHandler extends BaseServerHandler {


    public ConnectHandler(RemoteFactory remoteFactory) {
        super(remoteFactory);
    }

    @Override
    protected synchronized void handleO(ChannelHandlerContext ctx, Request inbound) {
        if (this.getRemoteFactory().hasClient(inbound.getClientId())) {
            Utils.sendError(ctx.channel(), inbound, "该客户端已连接");
            return;
        }
        String clientId = this.getRemoteFactory().generateClientId();
        ClientInfo clientInfo = (ClientInfo) inbound.getValue();
        clientInfo.setClientId(clientId);
        Response response = new Response();
        response.setIsSucceed(true);
        response.setClientId(clientInfo.getClientId());
        response.setCommand(inbound.getCommand());
        response.setValue(clientInfo);
        ctx.writeAndFlush(response);

        this.getRemoteFactory().addClient(new ServerClientInfo(clientInfo, ctx));
    }
}
